﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace StoreProject.OtherUtil
{
    public class DataProtector
    {
        public static readonly string SALT = "#%*(UI)";
        public static string EncryptLocalMachine(string data, string salt)
        {
            try
            {
                byte[] dataByte = Encoding.UTF8.GetBytes(data);
                byte[] saltByte = Encoding.UTF8.GetBytes(salt);
                byte[] result = ProtectedData.Protect(dataByte, saltByte, DataProtectionScope.LocalMachine);
                return Convert.ToBase64String(result);
            }
            catch (PlatformNotSupportedException ex)
            {
                ILog log = LogManager.GetLogger("DataProtector");
                log.Error("操作系统不支持", ex);
            }
            catch (CryptographicException ex)
            {
                ILog log = LogManager.GetLogger("DataProtector");
                log.Error("加密错误", ex);
            }
            catch (ArgumentException ex)
            {
                ILog log = LogManager.GetLogger("DataProtector");
                log.Error("参数错误", ex);
            }
            catch (Exception ex)
            {
                ILog log = LogManager.GetLogger("DataProtector");
                log.Error("EncryptLocalMachine错误", ex);
            }
            return string.Empty;
        }

        public static string DecryptLocalMachine(string data, string salt)
        {
            try
            {
                byte[] dataByte = Convert.FromBase64String(data);
                byte[] saltByte = Encoding.UTF8.GetBytes(salt);
                byte[] result = ProtectedData.Unprotect(dataByte, saltByte, DataProtectionScope.LocalMachine);
                return Encoding.UTF8.GetString(result);
            }
            catch (Exception ex)
            {
                ILog log = LogManager.GetLogger("DataProtector");
                log.Error("DecryptLocalMachine错误", ex);
            }
            return string.Empty;
        }
    }
}
